package org.phoenixframework.api.sys.util;

import org.phoenixframework.common.entity.SysDept;
import org.phoenixframework.common.tools.Constants;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelifeke
 * Email: hautxxxyzjk@163.com
 * DateTime: 2021/5/8 19:26
 * Description:
 */
public class DeptUtil {

    public static List<SysDept> build(List<SysDept> sysAuthorities) {
        List<SysDept> trees = new ArrayList<>();
        for (SysDept sysDept : sysAuthorities) {
            if (Constants.GOD.equals(sysDept.getParentId())) {
                sysDept.setLevel(1);
                trees.add(findChildren(sysDept, sysAuthorities));
            }
        }
        return trees;
    }

    private static SysDept findChildren(SysDept treeNode, List<SysDept> treeNodes) {
        treeNode.setChildren(new ArrayList<>());
        for (SysDept it : treeNodes) {
            if (treeNode.getId().equals(it.getParentId())) {
                int level = treeNode.getLevel() + 1;
                it.setLevel(level);
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }

}
